
<script lang="ts" setup>
    import MobileNav from './components/mobile-nav.vue';
    import MobileList from './components/mobile-list.vue';
    import MobileBox from './components/mobile-box.vue';
    import type { RouterData   } from "@/api/auth/types";
    import { Mobile_TOKEN_KEY} from "@/enums/CacheEnum";
    import AiservAPI from "@/api/aiserv";
    import { useRoute} from 'vue-router';
    
    const route = useRoute();
    const query:RouterData  = route.query;
    
    const Token = <string>localStorage.getItem(Mobile_TOKEN_KEY);
    const SessinoCode = ref('')
    const disabledvalue = ref(false);
    const modbileType = ref<string>('');
    const from = ref({
        stream:true,//是否开启流式输出
        emotion:true,//是否有表情
        welcome:true,//欢迎语
        session_type: "user"
    })
    // 获取创建新的坐席会话
    const fromseat = ref({
        stream:true,//是否开启流式输出
        request:'',
        character:'',
        certain_info:''
    })
    const modileList = ref([]);
    if (query.sessionType)modbileType.value=query.sessionType;else modbileType.value='10'
    // 获取新的会话code
    function obtaincode(data:boolean){
        if ((modileList.value.length==0||(modileList.value.length==1&&modileList.value[0].input_content==''))&&data) {
            ElMessage('已切换最新会话')
        }else{
            modileList.value.splice(0,modileList.value.length);
            //  区分是从训练客服进来 还是AI聊天
            if (JSON.stringify(route.query) === '{}') {
                AiservAPI.postsession(Token,from.value).then(res=>{
                    SessinoCode.value = res.data.session_code;
                    const obj ={output_content:'',input_content:'',loat:false,emotion:''};
                    // // 欢迎语
                    if ( res.data.welcome) {
                        obj.output_content = res.data.welcome
                        modileList.value.push(obj)
                    }      
                })
            }else{
                if (query.request)fromseat.value.request=query.request;
                if (query.character)fromseat.value.character=query.character;
                AiservAPI.postSeatSession(Token,fromseat.value).then(res=>{
                    SessinoCode.value = res.data.session_code;
                })  
            }
        }
    }
    // 提问ai回复
    function putquestion(data:any){ 
        disabledvalue.value = true;
        const obj ={output_content:'',input_content:data,loat:true,emotion:''};
        obj.output_content = '正在思考中...'
        modileList.value.push(obj);
        // 调用ai回复接口
        fetch(import.meta.env.VITE_APP_BASE_API+"/api/aiserv/answer",{
            method: 'POST',
            headers: {
                'token':Token,
                'Content-Type': 'application/json',
                // 其他必要的 headers
            },
            body: JSON.stringify({
                session_code: SessinoCode.value,
                question: data.replace(/\n/g, ''),
                session_type:modbileType.value
            }), // 将数据转换为 JSON 字符串
        }).then(response => {
            modileList.value[modileList.value.length-1].loat=false;
            modileList.value[modileList.value.length-1].output_content='';
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            // 获取可读流
            const reader = response.body.getReader();
            // 初始化一个变量来跟踪是否跳过了前两个字符
            let hasSkippedFirstTwoChars = false;
            return new ReadableStream({
                async start(controller) {
                    while(true){
                        const   { done, value} = await reader.read()
                        if (done) {
                            // 如果读取完成，关闭流
                            controller.close();
                            return;
                        }
                         // 如果是code 表情是true 会话code 才会进行操作
                        if (from.value.emotion==true&&!hasSkippedFirstTwoChars&&modbileType.value=='10') {
                            switch (new TextDecoder().decode(value).slice(0, 2)) {
                                case '愤怒':
                                    modileList.value[modileList.value.length-1].emotion = new TextDecoder().decode(value).slice(0, 2);
                                    break;
                                case '稍有'://稍有不满
                                    modileList.value[modileList.value.length-1].emotion = new TextDecoder().decode(value).slice(0, 4);
                                    break;
                                case '辱骂':
                                    modileList.value[modileList.value.length-1].emotion = new TextDecoder().decode(value).slice(0, 2);
                                    break;
                                case '高兴':
                                    modileList.value[modileList.value.length-1].emotion = new TextDecoder().decode(value).slice(0, 2);
                                    break;
                                case '不耐'://不耐烦
                                    modileList.value[modileList.value.length-1].emotion = new TextDecoder().decode(value).slice(0, 3);
                                    break;
                                case '一般':
                                    modileList.value[modileList.value.length-1].emotion = new TextDecoder().decode(value).slice(0, 2);
                                    break;
                                default:
                                    modileList.value[modileList.value.length-1].emotion ='';
                                    break;
                            }
                            if (new TextDecoder().decode(value).slice(0, 4)=='稍有不满') {
                                modileList.value[modileList.value.length-1].output_content +=new TextDecoder().decode(value).substring(4); 
                            }else if (new TextDecoder().decode(value).slice(0, 3)=='不耐烦') {
                                modileList.value[modileList.value.length-1].output_content +=new TextDecoder().decode(value).substring(3);
                            }else  if (new TextDecoder().decode(value).slice(0, 2)!='稍有'||new TextDecoder().decode(value).slice(0, 2)!='不耐') {
                                modileList.value[modileList.value.length-1].output_content +=new TextDecoder().decode(value).substring(2);
                            }
                            hasSkippedFirstTwoChars = true;
                        }else{
                            modileList.value[modileList.value.length-1].output_content +=new TextDecoder().decode(value)   
                        }                            
                    }
                }
            });
        }).then(stream => {
            // 可以选择将流转换为文本、JSON 或其他格式
            return new Response(stream).text();
        }).then(result => {
            disabledvalue.value = false;
        }) .catch(error => {
            console.error('Fetch error:', error);
           return ElMessage.error("系统出错");
        });
    }
    // 初始化调用
    obtaincode(false)
</script>
<!-- AI聊天页面 -->
<template>
    <section  class="w-full h-full  flex flex-col min-h-screen">
        <MobileNav :navname="'AI对话'" :navshow="true" />
        <div class="flex center-list pt-11 ">
            <div class="w-full flex flex-col relative h-full">
                <MobileList 
                :modileList="modileList"
                :disabledvalue="disabledvalue"
                :modbileType="modbileType"
                @refreshcode="obtaincode"
                />
                <MobileBox  :disabledvalue="disabledvalue" @searchtitle="putquestion"  />
            </div>
        </div>
    </section>
</template>

<style scoped>
.center-list{
    flex: 1;
    background-color: #ebeef5 !important;
    overflow: hidden;
    height: 100vh;
}

</style>